<template>
    <d2-container>
      <div class="handle-box">
      </div>
      <template slot="header">
        <el-input slot="header" :clearable="true" v-model="query.name" placeholder="名称" style="margin-bottom: 5px;width:200px;margin-right:10px"></el-input>
        <el-cascader slot="header"  v-model="query.module" :options="option.module.model" :props="option.module.props" change-on-select style="margin-bottom: 5px;width:200px;margin-right:10px"></el-cascader>
        <el-button slot="header" icon="el-icon-search" @click="handleSearch">查询</el-button>
        <el-button slot="header" icon="el-icon-refresh"  @click="handleRefresh">重置</el-button>
        <el-button slot="header" icon="el-icon-plus" type="button" @click="() => handleAdd()" v-hasBtn="'interface_add'">新增</el-button>
      </template>
      <el-table :data="list.data" border v-loading="list.loading" class="table" ref="multipleTable">
        <el-table-column prop="name" label="名称" width="260" v-if="hasCol('interface_name')">
        </el-table-column>
        <el-table-column prop="url" label="url" v-if="hasCol('interface_url')" >
        </el-table-column>
        <el-table-column prop="version" label="版本号"  width="120"  v-if="hasCol('interface_version')">
        </el-table-column>
        <el-table-column prop="method" label="method"  width="100"  v-if="hasCol('interface_method')">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.method=='GET'" type="success">GET</el-tag>
            <el-tag v-else-if="scope.row.method=='POST'" type="danger">POST</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态"  width="100"  v-if="hasCol('interface_status')">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status==1" type="success">使用中</el-tag>
            <el-tag v-else type="danger">已弃用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" align="center" v-if="hasCol('interface_edit')">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleNewVersion(scope.row)"  v-hasBtn="'interface_newVersion'">复制为新版本</el-button>
            <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)"  v-hasBtn="'interface_edit'">编辑</el-button>
            <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.row)"  v-hasBtn="'interface_del'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template slot="footer">
        <el-pagination background @size-change="handlePageSize" @current-change="handlePageIndex" :current-page="query.pageIndex" :page-sizes="[10, 20, 30, 50, 150, 200]" layout="total, sizes, prev, pager, next, jumper" :page-size="query.pageSize" :total="list.total">
        </el-pagination>
      </template>

    <!-- 编辑弹出框 -->
    <Drawer :title="form.type" v-model="form.show" width="80%" :mask-closable="false" :styles="styles">
      <el-row :gutter="20">
        <el-col :span="6" :offset="9">
          <el-steps :active="active" align-center finish-status="success">
            <el-step title="基本设置"></el-step>
            <el-step title="参数设置"></el-step>
          </el-steps>
        </el-col>
      </el-row>
      <el-form ref="form" :model="form.model" :rules="form.rules" label-width="120px">
        <div v-if="active === 0">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="名称" prop="name">
                <el-input v-model="form.model.name"></el-input>
              </el-form-item>  
            </el-col>
            <el-col :span="12">
              <el-form-item label="版本号" prop="name">
                <el-input v-model="form.model.version"></el-input>
              </el-form-item>  
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所属项目" prop="moduleId">
                <el-cascader v-model="form.model.module" :options="option.module.model" :props="option.module.props" @change="handleSelectModule" style="width:100%"></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Url"  prop="url">
                <el-input v-model="form.model.url"></el-input>
              </el-form-item>
            </el-col>
          </el-row>  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="DebugHost"  prop="debug">
                <el-input v-model="form.model.host.debug"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="OnlineHost"  prop="online">
                <el-input v-model="form.model.host.online"></el-input>
              </el-form-item>
            </el-col>
          </el-row>  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="Method"  prop="method">
                <el-select placeholder="请选择Method" v-model="form.model.method" class="handle-input" style="width:100%">
                  <el-option v-for="option in option.methods" :key='option.value' :value="option.value" :label="option.text" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="请求ContentType"  prop="requestContentType">
                <el-input v-model="form.model.requestContentType"></el-input>
              </el-form-item>
            </el-col>
          </el-row>     
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="服务端进度"  prop="serversProgresses">
                <el-select placeholder="请选择服务端进度" v-model="form.model.serversProgress" class="handle-input mr10" style="width:100%">
                  <el-option v-for="option in option.serversProgresses" :key='option.value' :value="option.value" :label="option.text" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="返回ContentType"  prop="responseContentType">
                <el-input v-model="form.model.responseContentType"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="使用JWT">
              <el-radio-group v-model="form.model.useJwt">
                <el-radio :label="false">否</el-radio>
                <el-radio :label="true">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">            
            <el-form-item label="状态">
              <el-radio-group v-model="form.model.status">
                <el-radio :label="'1'">使用中</el-radio>
                <el-radio :label="'0'">已弃用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        </div>
        <div v-if="active === 1">
          <el-tabs v-model="tabModel" @tab-click="handleTabClick" type="border-card" >
            <el-tab-pane label="Header" name="requestHeader">
                <json-editor ref="requestHeader" v-model="form.model.requestHeader" />
            </el-tab-pane>
            <el-tab-pane label="请求参数" name="requestParam">
                <el-button type="text" @click="handleAnnotation('requestParam')">生成注释</el-button>
                <el-row :gutter="10">
                  <el-col :span="12">
                    <json-editor ref="requestParam" v-model="form.model.requestParam" />
                  </el-col>
                  <el-col :span="12">
                    <el-table :data="form.model.requestParamDesc" border class="table" ref="requestParamDescTable">
                      <el-table-column prop="name" label="名称">
                      </el-table-column>
                      <el-table-column prop="type" label="类型" width="80px">
                      </el-table-column>
                      <el-table-column prop="isMust" label="必须" width="120px">
                        <template slot-scope="scope">
                          <el-select placeholder="" v-model="scope.row.isMust" class="handle-input mr10 table-select">
                            <el-option v-for="option in option.isMust" :key='option.value' :value="option.value" :label="option.text" />
                          </el-select>
                        </template>
                      </el-table-column>
                      <el-table-column prop="defaultValue" label="默认值">
                        <template slot-scope="scope">
                          <el-input v-model="scope.row.defaultValue"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column prop="remark" label="备注">
                        <template slot-scope="scope">
                          <el-input v-model="scope.row.remark"></el-input>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-col>
                </el-row>
            </el-tab-pane>
            <el-tab-pane label="返回参数" name="responseParam">
                <el-button type="text" @click="handleAnnotation('responseParam')">生成注释</el-button>
                <el-row :gutter="10">
                  <el-col :span="12">
                    <json-editor ref="responseParam" v-model="form.model.responseParam"/>
                  </el-col>
                  <el-col :span="12">
                    <el-table :data="form.model.responseParamDesc" border class="table" ref="responseParamDescTable">
                      <el-table-column prop="name" label="名称">
                      </el-table-column>
                      <el-table-column prop="type" label="类型" width="80px">
                      </el-table-column>
                      <el-table-column prop="defaultValue" label="示例">
                      </el-table-column>
                      <el-table-column prop="remark" label="备注">
                        <template slot-scope="scope">
                          <el-input v-model="scope.row.remark"></el-input>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-col>
                </el-row>
            </el-tab-pane>
            <el-tab-pane label="成功返回示例" name="responseSuccExam">
                <json-editor ref="responseSuccExam" v-model="form.model.responseSuccExam"/>
            </el-tab-pane>
            <el-tab-pane label="失败返回示例" name="responseErrExam">
                <json-editor ref="responseErrExam" v-model="form.model.responseErrExam"/>
            </el-tab-pane>            
          </el-tabs>
        </div>
      </el-form>
      <div class="iview-drawer-footer">
        <Button style="margin-right: 8px" @click="form.show = false">取 消</Button>
        <Button style="margin-right: 8px;" @click="next" v-if="active === 0">下一步</Button>
        <Button style="margin-right: 8px;" @click="last" v-if="active === 1">上一步</Button>
        <Button type="primary" @click="handleSaveEdit">确 定</Button>
      </div>
    </Drawer> 
    <el-dialog :title="'复制新版本'" :visible.sync="newVersionForm.show" width="30%">
      <el-form ref="newVersionForm" :model="newVersionForm.model" :rules="newVersionForm.rules" label-width="120px">
        <el-form-item label="版本号" prop="version">
          <el-input v-model="newVersionForm.model.version"></el-input>
        </el-form-item>  
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="newVersionForm.show = false">取 消</el-button>
        <el-button type="primary" @click="handleNewVersionSave">确 定</el-button>
      </span>
    </el-dialog>
    </d2-container>
</template>

<script>
    import { getPage,save,remove,copyNewVersion } from '@/api/interface/interface'
    import { moduleOption } from '@/api/option'
    import { isSelected } from '@/utils/validator'
    import jsonEditor from '@/components/JsonEditor'
    import { haveCol } from '@/utils/colPermissions'; // 列权限
    export default { 
        components: { jsonEditor },
        data() {
            return {
                styles: {
                    height: 'calc(100% - 55px)',
                    overflow: 'auto',
                    paddingBottom: '53px',
                    position: 'static'
                },
                active: 0,
                query: {
                    name: '',
                    moduleId: 0,
                    module:[],
                    pageIndex: 1,
                    pageSize: 10
                },
                list: {
                    loading: false,
                    total: 0,
                    data: []
                },
                option:{
                  module:{
                    model:[],
                    props:{
                      value: 'id',
                      label: 'name'
                    },
                  },
                  serversProgresses:[
                    {
                      text:"字段定义中",
                      value:"1"
                    },{
                      text:"假数据",
                      value:"2"
                    },{
                      text:"业务逻辑已实现",
                      value:"3"
                    }
                  ],
                  clientProgresses:[{
                      text:"尚未对接",
                      value:"1"
                    },{
                      text:"对接讨论中",
                      value:"2"
                    },{
                      text:"对接完成",
                      value:"3"
                    }
                  ],
                  methods:[
                    {
                      text:"POST",
                      value:"POST"
                    },{
                      text:"GET",
                      value:"GET"
                    }
                  ],
                  isMust:[
                    {
                      text:"必须",
                      value:'true'
                    },{
                      text:"可选",
                      value:'false'
                    }
                  ]
                },
                tabModel:'requestHeader',
                form:{
                  show:false,
                  type:"新增",
                  model:{
                    id:'',
                    name:"",
                    moduleId: '',
                    module:[],
                    description:"",
                    useJwt:false,
                    url:"",
                    sort:0,
                    status:'1',
                    version:'1.0.0',
                    serversProgress:'1',
                    clientProgress:'1',
                    requestHeader:{},
                    requestOther:{},
                    requestContentType:"application/json; charset=utf-8",
                    requestParam:{},
                    requestParamDesc:[],
                    responseContentType:"application/json; charset=utf-8",
                    responseParam:{},
                    responseSuccExam:{},
                    responseErrExam:{},
                    responseParamDesc:[],
                    host:{
                      debug:"",
                      online:""
                    }
                  },
                  rules: {
                      name: [
                          { required: true, message: '请输入名称', trigger: 'blur' }
                      ],
                      moduleId: [
                          { validator: isSelected, trigger: 'blur' }
                      ]
                  }
                },
                newVersionForm:{
                  show:false,
                  model:{
                    id:"",
                    version:""
                  },
                  rules: {
                      version: [
                          { required: true, message: '请输入版本号', trigger: 'blur' }
                      ],
                  }
                }
            }
        },
        created() {
            this.getListData();  
            this.getModuleOption();          
        },
        computed: {
            data() {
            }
        },
        methods: {
            next() {
              if (this.active++ > 1) this.active = 0;
            },
            last() {
              if (this.active-- < 0) this.active = 0;
            },
            getListData() {
              this.list.loading = true;
              if(this.query.module.length > 0){
                this.query.moduleId = this.query.module[this.query.module.length - 1]
              }
              getPage(this.query).then(res => {
                this.list.data = res.data.items;
                this.list.total = res.data.totalCount; 
                this.list.loading = false;
              })
            },
            getModuleOption(){
              moduleOption().then(res => {
                this.option.module.model = res.data
              })
            },
            handlePageSize(pageSize) {
                this.query.pageSize = pageSize
                this.getListData()
            },
            handlePageIndex(pageIndex) {
                this.query.pageIndex = pageIndex
                this.getListData()
            },
            handleSearch() {
                this.query.pageIndex = 1
                this.query.pageSize = 10
                this.getListData()
            },
            handleRefresh() {
              this.query = {
                name: '',
                moduleId: 0,
                module:[],
                pageIndex: 1,
                pageSize: 10
              }
              this.getListData()
            },
            handleAdd(){
              this.form.model = {
                    name:"",
                    moduleId: '',
                    module:[],
                    description:"",
                    useJwt:false,
                    sort:0,
                    url:"",
                    status:'1',
                    version:'1.0.0',
                    serversProgress:'',
                    clientProgress:'1',
                    requestHeader:{},
                    requestOther:{},
                    requestContentType:"application/json; charset=utf-8",
                    requestParam:{},
                    requestParamDesc:[],
                    responseContentType:"application/json; charset=utf-8",
                    responseParam:{},
                    responseSuccExam:{},
                    responseErrExam:{},
                    responseParamDesc:[],
                    host:{
                      debug:"",
                      online:""
                    }
              }
              this.active = 0
              this.form.type = "新增";
              this.form.show = true;
              window.setTimeout(() => {
                this.$refs.requestHeader.refresh()
              });
            },
            handleEdit(row){
              this.active = 0
              this.form.model = Object.assign({}, row)
              this.option.module.model.forEach(item => {
                if(item.children != null){
                  item.children.forEach(e => {
                    if(e.id == this.form.model.moduleId){
                      this.form.model.module = [item.id,e.id]
                    }
                  })
                }
              });
              this.form.type = "编辑"
              this.form.show = true
            },
            handleSaveEdit(){
              if(this.form.model.module.length > 0){
                this.form.model.moduleId = this.form.model.module[this.form.model.module.length - 1]
              }
              this.$refs["form"].validate((valid) => {
                if (valid) {
                  this.form.model.requestHeader = this.toJson(this.form.model.requestHeader)
                  this.form.model.requestOther = this.toJson(this.form.model.requestOther)
                  this.form.model.requestParam = this.toJson(this.form.model.requestParam)
                  this.form.model.responseParam = this.toJson(this.form.model.responseParam)
                  this.form.model.responseSuccExam = this.toJson(this.form.model.responseSuccExam)
                  this.form.model.responseErrExam = this.toJson(this.form.model.responseErrExam)
                  save(this.form.model).then(res => {
                    if (res.status === 200) {
                      this.form.show = false;
                      this.$message({
                        message: "操作成功",
                        type: "success"
                      });
                      this.getListData();
                    }else{
                      this.$message({ message: res.message, type: 'error' })
                    }
                  })
                  }
                  else{
                    this.$message({ message: "输入错误", type: 'error' })
                    return false;
                  }
                })
            },
            handleNewVersion(row){
              this.newVersionForm.model = {
                id: row.id,
                version: row.version
              }
              this.newVersionForm.show = true
            },
            handleNewVersionSave(){              
              this.$refs["newVersionForm"].validate((valid) => {
                if (valid) {
                  copyNewVersion(this.newVersionForm.model).then(res => {
                    if (res.status === 200) {
                      this.newVersionForm.show = false;
                      this.$message({
                        message: "操作成功",
                        type: "success"
                      });
                      this.getListData();
                    }else{
                      this.$message({ message: res.message, type: 'error' })
                    }
                  })
                }
                else{
                    this.$message({ message: "输入错误", type: 'error' })
                    return false;
                }
              })
            },
            handleDelete(data) {
              this.$confirm("此操作将永久删除, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              })
                .then(() => {
                  remove({ Id: data.id }).then(res => {
                    if (res.status === 200) {
                      this.form.show = false;
                      this.$message({
                        message: "删除成功",
                        type: "success"
                      });
                      this.getListData();
                    }
                  });
                })
                .catch(() => {
                  this.$message({
                    type: "info",
                    message: "已取消删除"
                  });
                });
            },
            handleTabClick(e){
              switch(e.name){
                case "requestHeader":
                  window.setTimeout(() => {
                    this.$refs.requestHeader.refresh()
                  });
                  break;
                case "requestParam":
                  window.setTimeout(() => {
                    this.$refs.requestParam.refresh()
                  });
                  break;
                case "responseParam":
                  window.setTimeout(() => {
                    this.$refs.responseParam.refresh()
                  });
                  break;
                case "responseSuccExam":
                  window.setTimeout(() => {
                    this.$refs.responseSuccExam.refresh()
                  });
                  break;
                case "responseErrExam":
                  window.setTimeout(() => {
                    this.$refs.responseErrExam.refresh()
                  });
                  break;
              }
            },
            handleAnnotation(e){
              if(e === 'requestParam'){
                var json = JSON.parse(this.$refs.requestParam.getValue())
                this.form.model.requestParamDesc = this.jsonToTable('','',json,[])
              }
              if(e === 'responseParam'){
                var json = JSON.parse(this.$refs.responseParam.getValue())
                this.form.model.responseParamDesc = this.jsonToTable('','',json,[])
              }
            },
            jsonToTable(parentKey,parentName,json,table){
              for(var key in json){
                var value = json[key]
                var name = key
                if(parentName !== ''){
                  name = parentName +'-->'+ key
                }
                let defaultValue = ''
                let remark = value
                if(typeof value === 'object' && value != null){
                  defaultValue = ''
                  remark = ''
                }else{
                  defaultValue = value
                }
                let typeofvalue = typeof value
                if(this.isArrayFn(value)){
                  typeofvalue = 'array'
                  value = value[0]
                  remark = typeof value + '数组'
                }
                table.push({
                  name: name,
                  key: key,
                  isMust: 'ture',
                  type: typeofvalue,
                  defaultValue: defaultValue,
                  remark: remark,
                  parentKey: parentName
                })
                if(typeof value === 'object' && value != null){
                  this.jsonToTable(key,name,value,table)
                }
              }
              return table
            },
            checkJson(e){
              try{
                JSON.parse(e)
                return true
              }
              catch(a){
                return false
              }
            },
            isArrayFn(value){
              if (typeof Array.isArray === "function") {
                return Array.isArray(value);
              }else{
                return Object.prototype.toString.call(value) === "[object Array]";
              }
            },
            toJson(e){
              return typeof e === 'string' ? JSON.parse(e) : e
            },
            hasCol(e){
              return haveCol(e)
            },
            handleSelectModule(e){
              if(e[0] !== "" && this.form.type === "新增")
              {
                var project = this.option.module.model.filter(o => o.id === e[0])[0]
                var module = project.children.filter(o => o.id === e[1])[0]
                this.form.model.url = module.url + "/"
                this.form.model.host = project.host
              }
            }
        }
    }

</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.table-select{
  width: 100px
}
.iview-drawer-footer{
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}
</style>
